package forJava;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hanj.cn@outlook.com
 */
public class ObjectToXmlUtil {

    public static void objectToXml(Object target, String fileName) throws IOException {

        if (fileName == null || "".equals(fileName)) {
            throw new RuntimeException("文件名不能为空!");
        }
        // 创建输出文件
        File file = new File(fileName);
        // 文件不存在,就报错
        if (!file.exists()) {
            throw new FileNotFoundException();
        }
        // 创建文件输出流
        FileOutputStream fos = new FileOutputStream(file);
        // 创建XML文件对象输出类实例
        XMLEncoder encoder = new XMLEncoder(fos);
        // 对象序列化输出到XML文件
        encoder.writeObject(target);
        // 刷新
        encoder.flush();
        // 关闭序列化工具
        encoder.close();
        // 关闭输出流
        fos.close();
        System.out.println("输出完毕");
    }

    public static List<Object> xmlToObject(String filePath) throws IOException {

        ArrayList<Object> objList = new ArrayList<>();
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        XMLDecoder decoder = new XMLDecoder(fis);
        Object obj;
        try {
            while ((obj = decoder.readObject()) != null) {
                objList.add(obj);
            }
        } catch (Exception ignored) {

        }

        fis.close();
        decoder.close();
        System.out.println("读取完毕");
        return objList;
    }

}

